<template>
  <div class="system-log">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="header-title">系统日志</span>
        </div>
      </template>

      <!-- 信息提示 -->
      <el-alert
        v-if="loading"
        title="正在加载系统日志..."
        type="info"
        :closable="false"
        show-icon
      />

      <el-alert
        v-if="error"
        :title="'加载失败: ' + error"
        type="error"
        :closable="false"
        show-icon
      />

      <!-- 显示日志 -->
      <pre v-if="logs.length > 0" class="log-content">{{ formattedLogs }}</pre>

      <el-alert
        v-else
        title="暂无系统日志"
        type="warning"
        :closable="false"
        show-icon
      />
    </el-card>
  </div>
</template>

<script>
import axios from 'axios'; // 导入 axios

export default {
  name: 'SystemLog',
  data() {
    return {
      logs: [],
      loading: true,
      error: null,
    };
  },
  computed: {
    formattedLogs() {
      // 如果有日志，拼接成多行显示
      return this.logs.join('\n');
    },
  },
  created() {
    this.fetchLogs();
  },
  methods: {
    async fetchLogs() {
      try {
        // 使用 axios 请求后端接口，设置请求地址为 localhost
        const response = await axios.get('http://localhost:8080/api/admin/logs/startup');
        
        if (response.data.code === 200) {
          // 请求成功后保存日志数据
          this.logs = response.data.data || [];
        } else {
          // 请求成功但是没有日志数据
          this.error = '没有返回日志数据';
        }
      } catch (err) {
        // 捕获请求失败的错误
        this.error = '请求失败: ' + (err.response ? err.response.data.message : err.message);
      } finally {
        // 无论请求成功还是失败，都结束加载状态
        this.loading = false;
      }
    },
  },
};
</script>

<style scoped>
.system-log {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.log-content {
  white-space: pre-wrap;
  word-wrap: break-word;
  margin-top: 20px;
  font-size: 14px;
  line-height: 1.6;
  color: #333;
  background-color: #f4f4f4;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.el-alert {
  margin-top: 10px;
}

.el-alert .el-alert__content {
  font-size: 14px;
}
</style>
